package com.colorlight.cloud.complete.entity.instructions;

import com.colorlight.cloud.common.exception.ParameterException;
import com.colorlight.cloud.common.model.ExceptionEnum;
import com.colorlight.cloud.complete.api.CompleteEntityScheduleActions;
import com.colorlight.cloud.complete.entity.po.Location;
import com.colorlight.iot.proto.complete.entity.CompleteEntity;
import com.colorlight.iot.proto.complete.instruction.CompleteInstruction;
import com.google.protobuf.*;
import lombok.*;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.util.Map;
import java.util.Objects;

/**
 * @author Demon
 * @description 主动获取设备地址
 * @date 30/5/2024  下午1:51
 */

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Slf4j
public class GetLocation implements CompleteEntityScheduleActions {
	
	@Override
	public ByteString objectConvertBytes() {
		final CompleteInstruction.GetLocation.InputMsg.Builder inputMsgBuilder =
				CompleteInstruction.GetLocation.InputMsg.newBuilder();
		
		final CompleteInstruction.GetLocation.Builder builder =
				CompleteInstruction.GetLocation.newBuilder();
		builder.setInput(inputMsgBuilder);
		return builder.build().toByteString();
	}
	
	@Override
	public GetLocation byteConvertObject(ByteString bytes) {
		CompleteInstruction.GetLocation getLocation = null;
		try {
			getLocation = CompleteInstruction.GetLocation.parseFrom(bytes);
		} catch (InvalidProtocolBufferException e) {
			log.error("", e);
		}
		if (Objects.isNull(getLocation)) {
			throw new ParameterException(ExceptionEnum.MSG_PARAMETER_EXCEPTION);
		}
		CompleteInstruction.GetLocation.OutputMsg output = getLocation.getOutput();
		GetLocation.OutputMsg locationOutputMsg = new OutputMsg();
		Descriptors.Descriptor descriptorForType = output.getDescriptorForType();
		Descriptors.FieldDescriptor networkType = descriptorForType.findFieldByName("location");
		Map<Descriptors.FieldDescriptor, Object> allFields = output.getAllFields();
		if (Objects.nonNull(networkType)&&allFields.containsKey(networkType)) {
			locationOutputMsg.setLocation(new Location().formProto(output.getLocation()));
		}
		this.setOutputMsg(locationOutputMsg);
		return this;
	}
	
	@Data
	@NoArgsConstructor
	@Builder
	public static class InputMsg implements Serializable {
	}
	
	@Data
	@NoArgsConstructor
	@AllArgsConstructor
	@Builder
	public static class OutputMsg implements Serializable {
		/**
		 * 返回位置信息，不存在则为null
		 */
		private Location location ;
	}
	
	private InputMsg inputMsg;
	private OutputMsg outputMsg;
	
}